package com.dean.ui.panel.impl;

import com.dean.action.CodeGenAction;
import com.dean.constants.DeanUiConstants;
import com.dean.entity.DeanDbConnInfo;
import com.dean.entity.DeanResponse;
import com.dean.entity.SysDbConnInfo;
import com.dean.service.DbConnService;
import com.dean.ui.panel.DeanPanel;
import com.dean.ui.utils.UiUtils;
import com.dean.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName CsvImpExpPanel
 * @Description csv 导入面板
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class CodeGenPanel extends BasePanel implements DeanPanel {

    private static final Logger logger = LoggerFactory.getLogger(CodeGenPanel.class);
    /**
     * 配置 文件路径
     */
    private final String INIT_PATH_NAME = DeanUiConstants.INIT_PATH + "codegen.properties";
    /**
     * 模板组件
     */
    private List<JCheckBox> ftls;
    /**
     * 选中模板
     */
    private List<String> ftlNames = new ArrayList<String>(16);

    /**
     * 左上布局 左 上 1 文件导出目录
     */
    private JLabel filePathLable;
    private JTextField filePathInput;
    /**
     * 左上布局 左 上 2 包名
     */
    private JLabel packageNameLabel;
    private JTextField packageNameInput;
    /**
     * 左上布局 左 上 3 tableName
     */
    private JTextArea tableName;

    /**
     * 右上 1
     */
    private JLabel connNameLable;
    private JComboBox<String> connName;

    /**
     * 右上 6 保存按钮
     */
    private JButton saveCfgBtn;

    /**
     * 中间
     */
    private JButton crtEntityBtn;

    private JTextArea exeLog;

    private JCheckBox allSelected;
    private JCheckBox invertSelected;

    private JScrollPane fieldSqlScroll;

    @Override
    public void mainUi() {
        int startRow = 1;
        connNameLable = new JLabel("connName:");
        UiUtils.setRightBounds(connNameLable,startRow);
        panel.add(connNameLable);
        connName = new JComboBox<String>();
        UiUtils.setRightBounds(connName,startRow);
        panel.add(connName);

        // sql输入窗口
        tableName = new JTextArea();
        tableName.setEditable(true);
        fieldSqlScroll = new JScrollPane(tableName);
        UiUtils.setTextAreaBounds(fieldSqlScroll,startRow,4,1);
        UiUtils.setTextAreaBounds(fieldSqlScroll,startRow,4,1);
        panel.add(fieldSqlScroll);
        startRow++;

        filePathLable = new JLabel("请输入文件路径:");
        UiUtils.setRightBounds(filePathLable,startRow);
        panel.add(filePathLable);

        filePathInput = new JTextField();
        UiUtils.setRightBounds(filePathInput,startRow);
        panel.add(filePathInput);
        startRow++;

        packageNameLabel = new JLabel("basePackage:");
        UiUtils.setRightBounds(packageNameLabel,startRow);
        panel.add(packageNameLabel);

        packageNameInput = new JTextField();
        UiUtils.setRightBounds(packageNameInput,startRow);
        panel.add(packageNameInput);
        startRow++;

        saveCfgBtn = new JButton("保存配置信息");
        UiUtils.setRightButtonBounds(saveCfgBtn,startRow,1);
        panel.add(saveCfgBtn);
        // 执行按钮
        crtEntityBtn = new JButton("代码生成");
        UiUtils.setRightButtonBounds(crtEntityBtn,startRow,2);
        panel.add(crtEntityBtn);
        startRow++;

        allSelected = new JCheckBox("全选");
        UiUtils.setJCheckBoxBounds(allSelected,startRow,1,1);
        panel.add(allSelected);

        invertSelected = new JCheckBox("反选");
        UiUtils.setJCheckBoxBounds(invertSelected,startRow,1,2);
        panel.add(invertSelected);

        startRow++;
        // 查询列表窗口
        exeLog = new JTextArea();
        exeLog.setEditable(false);
        JScrollPane jScrollPane = new JScrollPane(exeLog);
        UiUtils.setTextAreaBounds(jScrollPane,startRow,-1,1,2);
        UiUtils.setTextAreaBounds(exeLog,startRow,-1,1,2);
        panel.add(jScrollPane);

        initFtls();

    }

    @Override
    public void mainScript() {
        // 下拉框处理
        DbConnService.getInstance().getConnInfos().forEach(connInfo -> {
            connName.addItem(connInfo.getConnName());
        });
        connName.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String connNameSelected = e.getItem().toString();
                    logger.debug("当前选中了{}", connNameSelected);
                }
            }
        });

        saveCfgBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 配置文件默认路径
                if (saveProperties()) {
                    JOptionPane.showMessageDialog(panel, "配置信息保存成功", "SUCESS", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(panel, "配置信息保存失败", "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        crtEntityBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                codeGen();
            }
        });

        allSelected.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(allSelected.isSelected()){
                    ftls.forEach(ftl ->{
                        ftl.setSelected(true);
                    });
                }
            }
        });

        invertSelected.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                ftls.forEach(ftl ->{
                    if(ftl.isSelected()){
                        ftl.setSelected(false);
                    }else{
                        ftl.setSelected(true);
                    }
                });
            }
        });
    }


    /**
     * 创建实体类
     */
    private void codeGen() {
        // 情况选中表
        ftlNames.clear();
        // 获取选中模板
        ftls.forEach(ftl->{
            logger.info(ftl.getText()+ ftl.isSelected());
            if(ftl.isSelected()){
                ftlNames.add(ftl.getText());
            }
        });
        String tableNames = tableName.getText();
        String [] tables = tableNames.split(",");
        String filePath = filePathInput.getText();
        String packageName = packageNameInput.getText();
        CodeGenAction genAction = CodeGenAction.getInstance();
        DeanResponse deanResponse = genAction.gen(initDbConnect(),tables,filePath,packageName,ftlNames);
        if(deanResponse.getCode() == 0){
            JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "ERROR", JOptionPane.ERROR_MESSAGE);
        }

    }

    /**
     * 初始化模板选项
     */
    private void initFtls(){
        // resource 文件
        // FileUtils.resourceFileCopy();
        // 读取模板
        File ftlPath = new File(FreemarkerUtils.TEMPLATE_PATH);
        File [] files = ftlPath.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".ftl");
            }
        });
        ftls = new ArrayList<JCheckBox>(16);
        files = files == null?new File[0]:files;
        for (File file : files) {
            ftls.add(new JCheckBox(file.getName().replace(".ftl","")));
        }

        for (int i = 1; i <= ftls.size(); i++) {
            JCheckBox ftl = ftls.get(i-1);
            UiUtils.setJCheckBoxBounds(ftl,5,1,i+2);
            panel.add(ftl);
        }
    }


    /**
     * 保存配置文件
     *
     * @return
     */
    private boolean saveProperties() {
        Properties properties = new Properties();
        // 读取 接口地址 db_driver db_url db_username db_password
        properties.setProperty("filePathInput", filePathInput.getText());
        properties.setProperty("packageName", packageNameInput.getText());
        properties.setProperty("tableNames", tableName.getText());
        properties.setProperty("connName", connName.getSelectedItem().toString());
        return PropertyUtils.saveProperties(INIT_PATH_NAME, properties);
    }

    /**
     * 初始化配置信息
     */
    @Override
    public void initProperties() {
        //初始化基础参数
        Properties properties = PropertyUtils.readProperties(INIT_PATH_NAME);
        if (properties != null) {
            connName.setSelectedItem(properties.getProperty("connName"));
            filePathInput.setText(properties.getProperty("filePathInput"));
            packageNameInput.setText(properties.getProperty("packageName"));
            tableName.setText(properties.getProperty("tableNames"));
        }else{
            saveProperties();
        }
    }


    /**
     * 设置数据库连接配置
     */
    private SysDbConnInfo initDbConnect() {
        SysDbConnInfo connectInfo = new SysDbConnInfo();
        connectInfo.setConnName(connName.getSelectedItem().toString());
        return connectInfo;
    }

}
